﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp.Demos.SimplePipeline
{
    public class HttpListenerServerByCustom : IServerByCustom
    {
        private readonly HttpListener _httpListener;
        private readonly string[] _urls;


        public HttpListenerServerByCustom(params string[] urls)
        {
            _httpListener = new HttpListener();
            _urls = urls.Any() ? urls : new string[] { "http://localhost:5000/" };
            Console.WriteLine("服务器启动 " + String.Join(',', _urls));
        }

        public async Task StartAsync(RequestDelegateByCustom handler)
        {
            Array.ForEach(_urls, url =>
            {
                _httpListener.Prefixes.Add(url);
            });

            _httpListener.Start();

            while (true)
            {
                // HttpListenerContext 是框架提供的一个对象
                // 这个里面包含了全部的 HTTP 请求/相应对象
                var listenerContext = await _httpListener.GetContextAsync();

                // 将 HttpListenerContext 转换为一个自定义的 HttpListenerFeature
                // 它包括请求和相应
                var listenerFeature = new HttpListenerFeatureByCustom(listenerContext);

                // 将请求和响应
                // 封装在一个包含自定义请求和响应接口的集合中
                var features = new FeatureCollectionByCustom()
                    .Set<IHttpRequestFeatureByCustom>(listenerFeature)
                    .Set<IHttpResponseFeatureByCustom>(listenerFeature);

                // 通过从义集合中获取 IHttpRequestFeature 和 IHttpResponseFeature
                // 然后构建一个自定义的 HttpContext
                // 它表示整个的 Http 上下文
                var httpContext = new HttpContextByCustom(features);

                // 构建好了 contxt
                // 交给自定义的管道处理
                await handler(httpContext);

                // 处理完成后
                // 关闭最后的响应
                listenerContext.Response.Close();
            }
        }
    }
}
